package main;

import gui.Guimap;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import pathfinding.Pathfinding;

import runner.Enemy;
import towers.Projectile;
import towers.Tower;

public class TDMap extends Observable implements Observer {
	
	private Map<Coord, Tower> towers;
	private boolean[][] pathmap;
	private List<Coord> bestPath;
	Coord start, finish;
	private Set<Enemy> enemies;
	private Set<Projectile> projectiles;
	private Ticker ticker;
	
	public TDMap(int width, int height, Ticker ticker) {
		this.ticker = ticker;
		start = new Coord(0, Guimap.MAP_HEIGHT/2);
		finish = new Coord(Guimap.MAP_WIDTH-1, Guimap.MAP_HEIGHT/2);
		towers = new HashMap<Coord, Tower>();
		pathmap = new boolean[width][height];
		projectiles = new HashSet<Projectile>();
		updatePath();
	}
	
	public Map<Coord, Tower> getTowerMap() {
		return towers;
	}
	
	public void addTower(Coord c, Tower t) {
		towers.put(c, t);
		pathmap[c.x][c.y] = true;
		updatePath();
		this.setChanged();
		this.notifyObservers();
	}
	
	public void setEnemies(Set<Enemy> enemies) {
		this.enemies = enemies;
	}
	
	public Set<Enemy> getEnemies() {
		return enemies;
	}
	
	public void killEnemy(Enemy e) {
		enemies.remove(e);
	}
	
	private void updatePath() {
		bestPath = Pathfinding.find(start, finish, pathmap);
	}
	
	public boolean[][] getPathMap() {
		return pathmap;
	}
	
	public List<Coord> getPath() {
		return bestPath;
	}
	
	public void addProjectile(Projectile p) {
		projectiles.add(p);
		p.addObserver(this);
		ticker.addTickable(p);
	}
	
	public Set<Projectile> getProjectiles() {
		return projectiles;
	}

	@Override
	public void update(Observable obs, Object arg1) {
		if (obs instanceof Projectile) {
			Projectile p = (Projectile)obs;
			if (p.isDead()) {
				projectiles.remove(p);
			}
		}
		
	}
}
